<?php

/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/25
 * Time: 9:48
 */

namespace app\api\controller\android\v13;


use app\api\model\Aliyunoss;
use app\api\model\Authority;

use app\api\model\ConstructionNode;
use think\Controller;
use app\api\model\Common;

use think\Request;


use think\Db;


class SiteInspection extends Controller
{
    protected $model;
    protected $us;


    public function _initialize()
    {
        $this->model = new Authority();
        $this->us    = Authority::check(1);
    }

    public function getList()
    {
        $data             = Authority::param(['orderId', 'type']);
        $ConstructionNode = new ConstructionNode();
        $capital          = $ConstructionNode->List($data['orderId'], $data['type']);
        $fast_salary      = db('order_setting')->where('order_id', $data['orderId'])->value('fast_salary');
        $title            = "";
        if ($fast_salary == 2) {
            $title = "店长验收通过后，师傅不用等订单结算便可周结50-80%工资，请认真对待，虚假上传及审核，触碰红线， 10倍处罚(点击查看详情)";
        }
        r_date(['data' => $capital, 'title' => $title], 200);
    }
    public function newGetList()
    {

        $data             = Authority::param(['orderId', 'type']);
        $ConstructionNode = new ConstructionNode();
        // $ConstructionNode->initial($data['orderId']);
        $capital          = $ConstructionNode->Lists($data['orderId'], $data['type']);
        $fast_salary      = db('order_setting')->where('order_id', $data['orderId'])->value('fast_salary');
        $title            = "";
        if ($fast_salary == 2) {
            $title = "店长验收通过后，师傅不用等订单结算便可周结50-80%工资，请认真对待，虚假上传及审核，触碰红线， 10倍处罚(点击查看详情)";
        }
        r_date(['data' => $capital, 'title' => $title], 200);
    }


    public function info()
    {

        $data                = Authority::param(['id']);
        $param = Request::instance()->post();
        if (isset($param['capitalId'])) {
            $capitalId = $param['capitalId'];
            $auxiliary_delivery_schedule = db('auxiliary_delivery_schedule')
                ->where('auxiliary_delivery_schedule.capital_id', $capitalId)
                ->where('auxiliary_delivery_schedule.work_process_id', $data['id'])
                ->whereNull('auxiliary_delivery_schedule.delete_time')
                ->select();

            $img = [];
            foreach ($auxiliary_delivery_schedule as  $item) {
                if ($item['work_process_accept_std_type'] == 1) {
                    $list['acceptance_criteria'][] = $item['work_process_accept_std_desc'];
                    $work_process_accept_std_sample_img = json_decode($item['work_process_accept_std_sample_img'], true);
                    if ($work_process_accept_std_sample_img) {
                        foreach ($work_process_accept_std_sample_img as  $value) {
                            array_push($img, $value);
                        }
                    }

                    $list['picture_url'] = $img;
                }
            }
            $list['acceptance_criteria'] = implode('<br>', $list['acceptance_criteria']);
        } else {
            $list                = db('auxiliary_delivery_schedule')
                ->join('auxiliary_interactive', 'auxiliary_interactive.id=auxiliary_delivery_schedule.auxiliary_interactive_id', 'left')
                ->field('auxiliary_interactive.shot,auxiliary_interactive.acceptance_criteria,auxiliary_interactive.picture_url,auxiliary_delivery_schedule.auxiliary_interactive_id')
                ->where('auxiliary_delivery_schedule.id', $data['id'])
                ->find();
            $list['picture_url'] = empty($list['picture_url']) ? [] : unserialize($list['picture_url']);
        }


        r_date($list, 200);
    }
    /**
     * 验收标准
     * 
     * @return void
     */
    public function acceptanceCriteria()
    {

        $data                = Authority::param(['capitalId', 'workId']);
        $auxiliary_delivery_schedule = db('auxiliary_delivery_schedule')
            ->field(
                ' auxiliary_delivery_schedule.work_process_accept_std_upload_ckp,
            
                auxiliary_delivery_schedule.work_process_accept_std_type,
                auxiliary_delivery_schedule.detailed_id,
                auxiliary_delivery_schedule.work_process_accept_std_desc,
                auxiliary_delivery_schedule.work_process_accept_std_sample_img,
               auxiliary_delivery_schedule.completion_time,
                auxiliary_delivery_schedule.work_process_accept_std_ai_acpt_std,
                auxiliary_delivery_schedule.work_process_accept_std_upload_req,
               auxiliary_delivery_node.state,
                group_concat(auxiliary_delivery_node.ai_score ORDER BY auxiliary_delivery_node.adn_id DESC SEPARATOR "&&&") as ai_score,
                group_concat(auxiliary_delivery_node.ai_content  ORDER BY auxiliary_delivery_node.adn_id DESC SEPARATOR "&&&") as ai_content,
                group_concat(auxiliary_delivery_node.roomid) as roomid,
                  
                 capital.cooperation,
                auxiliary_delivery_node.type,
                auxiliary_delivery_schedule.id,
                group_concat(auxiliary_delivery_node.node_id) as node_ids,
                group_concat(auxiliary_delivery_node.adn_id) as adn_id'
            )
            ->join('auxiliary_delivery_node', 'auxiliary_delivery_node.auxiliary_delivery_schedul_id=auxiliary_delivery_schedule.id and auxiliary_delivery_node.state=0', 'left')
            ->join('capital', 'capital.capital_id=auxiliary_delivery_schedule.capital_id', 'left')
            ->where('auxiliary_delivery_schedule.capital_id', $data['capitalId'])
            ->where('auxiliary_delivery_schedule.work_process_id', $data['workId'])
            ->whereNull('auxiliary_delivery_schedule.delete_time')
            ->group('auxiliary_delivery_schedule.id')
            ->select();
        $ai = [];

        foreach ($auxiliary_delivery_schedule as $k => $item) {
            if ($item['work_process_accept_std_type'] == 3) {
               
                if ($item['node_ids']) {
                    $app_user_order_nodes_list = Db::connect(config('database.db2'))->table('app_user_order_node')
                        ->join('app_user', 'app_user.id=app_user_order_node.user_id', 'left')
                        ->join(config('database')['database'] . '.user', 'user.user_id=app_user_order_node.user_id', 'left')
                        ->field('app_user_order_node.id,app_user_order_node.resource_ids,app_user_order_node.no_watermark_image_ids,app_user_order_node.created_at,if(app_user_order_node.distinguish=1,user.username,app_user.username) as username,app_user_order_node.distinguish')
                        ->whereIn('app_user_order_node.id', $item['node_ids'])->select();
                    $Img = [];
                    foreach ($app_user_order_nodes_list as  $value) {
                        $pathId                    = $value['resource_ids'];
                        $username = $value['username'];
                        if ($item['type'] == 3) {
                            $pathId                    = $value['no_watermark_image_ids'];
                            $username = '后台上传';
                        }
                        $path                      = Db::connect(config('database.db2'))->table('common_resource')->where('status', 1)->whereIn('id', $pathId)->field('mime_type,path,id')->select();

                        foreach ($path as $k1 => $o) {

                            $listArray['path']       = 'https://images.yiniao.co/' . $o['path'];
                            $listArray['id'] =  $item['adn_id'];
                            $listArray['state'] =  $item['state'];
                            $listArray['type']       = $value['distinguish'];
                            $listArray['no_watermark_image_ids'] = $value['no_watermark_image_ids'];

                            $listArray['username']   = $username;
                            $listArray['created_at'] = date('Y-m-d H:i', $value['created_at']);
                            $Img[] = $listArray;
                        }
                    }
                    $auxiliary_delivery_schedule[$k]['Img'] = $Img;
                } else {
                    $auxiliary_delivery_schedule[$k]['node_ids'] = []; // 没有节点数据时设为空数组
                    $auxiliary_delivery_schedule[$k]['Img'] = null;
                }
            }
        }



        $list = [];
        $img = [];
        $hide = 0;
        foreach ($auxiliary_delivery_schedule as $item) {
            switch ($item['work_process_accept_std_type']) {
                case 2:
                    $list['acceptance_criteria'][] = $item['work_process_accept_std_desc'];
                    $list['acceptance_ai'][] = $item['work_process_accept_std_ai_acpt_std'];
                    $sampleImg = json_decode($item['work_process_accept_std_sample_img'], true) ?: [];
                    $img = array_merge($img, $sampleImg);
                    break;
                case 3:
                    $list['shot'][] = $item['work_process_accept_std_desc'];
                    $sampleImg = json_decode($item['work_process_accept_std_sample_img'], true) ?: [];

                    // 避免重复添加 date 项
                    if (isset($list['date'])) {
                        $existingIds = array_column($list['date'], 'id');
                        if (in_array($item['id'], $existingIds)) {
                            continue;
                        }
                    }
                    //0是展示1隐藏

                    if (!empty($item['Img']) && $item['Img'][0]['state'] != 3) {

                        $hide = 1;
                    }
                     $ai_title = '';
                     $ai_content='';
                     $roomid='';
                    if ($item['detailed_id'] == 10032) {
                        $ai_score=explode("&&&",$item['ai_score'])[0];
                        $ai_title = '此组照片经过小益火眼金睛查看，找到如下问题，总分为:' . $ai_score . '分。按照标准可能不合格，请您再次过目看看。';
                        $ai_content = '';
                        $roomid = $item['roomid'];
                        if ($ai_score < 4) {
                            $ai_content =explode("&&&",$item['ai_content'])[0];;
                        }
                    }
                    $list['date'][] = [
                        'title' => $item['work_process_accept_std_upload_ckp'],
                        'id' => $item['id'],
                        'state' => empty($item['completion_time']) ? 0 : 1,
                        'cooperation' => $item['cooperation'],
                        'ai_title' => $ai_title,
                        'ai_content' => $ai_content,
                        'roomid' => $roomid,
                        'uploadReq' => $item['work_process_accept_std_upload_req'],
                        'exampleImg' => empty($sampleImg) ? null : $sampleImg,
                        'listImg' => empty($item['Img']) ? null : $item['Img']
                    ];
                    break;
            }
        }
        $list['shot'] = implode('<br>', $list['shot']);
        $list['hide'] = $hide;
        $list['acceptance_criteria'] = implode('<br>', $list['acceptance_criteria']);
       
        r_date($list, 200);
    }
       /**
     * 驳回记录
     * 
     * @return void
     */
    public function rejectionRecord()
    {

        $data                = Authority::param(['capitalId', 'workId']);
        $auxiliaryInspection = Db::connect(config('database.db2'))->table('auxiliary_inspection')
            ->field([
                'auxiliary_delivery_schedule.work_process_accept_std_upload_ckp as title',
                'auxiliary_inspection.node_id',
                'auxiliary_inspection.voucher',
                // case 优化：else 显示“未知”更友好，避免直接显示原始数字
                'case 
        when auxiliary_inspection.admin_type = 1 then "店长" 
        when auxiliary_inspection.admin_type = 2 then "师傅" 
        when auxiliary_inspection.admin_type = 3 then "BI系统" 
        when auxiliary_inspection.admin_type = 4 then "CC系统" 
        else "未知"  
     end as adminType',
                // concat 优化：处理空值+添加分隔符，避免拼接异常
                'concat(
        ifnull(auxiliary_inspection.admin_name, "未知管理员"), 
        "（", 
        FROM_UNIXTIME(auxiliary_inspection.create_time, "%Y-%m-%d %H:%i:%s"), 
        "）"
    ) as adminName',
                'user.username',
                'auxiliary_inspection.content'
            ])
            ->join('auxiliary_delivery_schedule', 'auxiliary_delivery_schedule.capital_id=auxiliary_inspection.capital_id  and auxiliary_delivery_schedule.work_process_id=auxiliary_inspection.work_process_id', 'left')
            ->join('user', 'auxiliary_inspection.user_id=user.user_id  ', 'left')

            ->where('approval_status', 2)

            ->where('work_process_accept_std_type', 3)

            ->where('auxiliary_inspection.capital_id', $data['capitalId'])
            ->where('auxiliary_inspection.work_process_id', $data['workId'])
            ->group('auxiliary_inspection.id')
            ->select();
        if (empty($auxiliaryInspection)) {
            r_date(null, 200);
        }

        // 3. 批量获取node_id（避免循环查库，减少N+1问题）
        $nodeIds = array_filter(array_column($auxiliaryInspection, 'node_id'));
        $nodeMap = [];
        if (!empty($nodeIds)) {
            // 一次性查询所有关联的节点数据
            $appUserOrderNodes =  Db::connect(config('database.db2'))->table('app_user_order_node')
                ->alias('aun')
                ->join('app_user au', 'au.id = aun.user_id', 'left')
                ->join(config('database.database') . '.user u', 'u.user_id = aun.user_id', 'left')
                ->field('aun.id, aun.resource_ids, aun.no_watermark_image_ids, aun.created_at, 
                    if(aun.distinguish=1, u.username, au.username) as username, aun.distinguish')
                ->whereIn('aun.id', $nodeIds)
                ->select();

            // 构建node_id => 节点数据的映射（避免循环查询）
            foreach ($appUserOrderNodes as $node) {
                $nodeMap[$node['id']] = $node;
            }

            // 批量获取资源ID（再次减少循环查库）
            $resourceIds = [];
            foreach ($appUserOrderNodes as $node) {
                if (!empty($node['resource_ids'])) {
                    $resourceIds = array_merge($resourceIds, explode(',', $node['resource_ids']));
                }
            }
            $resourceIds = array_unique(array_filter($resourceIds));
            $resourceMap = [];
            if (!empty($resourceIds)) {
                $resources =  Db::connect(config('database.db2'))->table('common_resource')
                    ->where('status', 1)
                    ->whereIn('id', $resourceIds)
                    ->field('id, mime_type, path')
                    ->select();
                // 构建资源ID => 资源路径的映射
                foreach ($resources as $res) {
                    $resourceMap[$res['id']] = $res;
                }
            }
        }

        // 4. 数据处理（循环内仅内存操作，无数据库查询）
        foreach ($auxiliaryInspection as $k => &$item) {
            // 处理图片数据（基于预查询的映射）
            $Img = [];
            if (!empty($item['node_id'])) {
                $nodeIdArr = explode(',', $item['node_id']); // 支持多个node_id
                foreach ($nodeIdArr as $nid) {
                    if (isset($nodeMap[$nid])) {
                        $node = $nodeMap[$nid];
                        $username = $node['username'];
                        $createdAt = date('Y-m-d H:i', $node['created_at']);

                        // 处理资源路径
                        if (!empty($node['resource_ids'])) {
                            foreach (explode(',', $node['resource_ids']) as $rid) {
                                if (isset($resourceMap[$rid])) {
                                    $Img[] = [
                                        'path' => 'https://images.yiniao.co/' . $resourceMap[$rid]['path'],
                                        'username' => $username,
                                        'created_at' => $createdAt
                                    ];
                                }
                            }
                        }
                    }
                }
            }
            $item['Img'] = $Img;

            // 处理其他字段
            $item['adminType'] = $item['adminType'] . '-' . ($item['username'] ?? '未知用户');
            $item['voucher'] = empty($item['voucher']) ? null : explode(',', $item['voucher']);

            // 清理无用字段
            unset($item['username'], $item['node_id']);
        }
        unset($item); // 释放引用

        r_date($auxiliaryInspection, 200);
    }
    /**
     * 益鸟AI验收?我有问题要反馈>
     */
    public function analyzeYiniaoAiFeedback()
    {
        $data                = Authority::param(['roomid', 'capitalId', 'content', 'type', 'workId','id']);
        $create_time = time();
        $capital = db('capital')->where('capital_id', $data['capitalId'])->find();
        $order = db('order')->join('order_info', 'order.order_id=order_info.order_id', 'left')->where('order.order_id',$capital['ordesr_id'])->field('order_info.assignor,order.order_no')->find();
        db('auxiliary_delivery_node')->where('auxiliary_delivery_schedul_id', $data['id'])->update(['retroaction'=>$data['type'],'remarks'=>$data['content']]);
        $title='AI验收挺准确';
        if($data['type']==2){
            $title='AI验收不准确';
        }
        $sendtxt = '店长姓名：' . $order['assignor'] .'
反馈时间：' . date('Y-m-d H:i:s', $create_time) . '
订单编号：' . $order['order_no'] . '
清单名称:' . $capital['class_b'] . $capital['projectId'] . '
反馈分类:' . $title . '
反馈内容:' . $data['content'];
         Db::connect(config('database.zong'))->table('wx_send')->insert(['room_id' => $data['roomid'], 'room_name' => '', 'phone' => '', 'sendtxt' => $sendtxt, 'create_time' => $create_time,'issend'=>9,'types'=>7]);
        r_date(null, 200);
    }
    /**
     * 走老的巡检还是新的巡检
     * @return never
     */
    public function isOld()
    {
        $data                = Authority::param(['orderId']);
        $change_work_time = db('order_times')->where('order_id', $data['orderId'])->value('change_work_time');
        $state = 0;
        if ($change_work_time > 1748534400) {
            $state = 1;
        }
        r_date($state, 200);
    }

    public function toExamine()
    {
        $data = Request::instance()->post();
        $list = db('app_user_order_capital')
            ->join('app_user', 'app_user.id=app_user_order_capital.user_id', 'left')
            ->where('app_user_order_capital.work_time', 0)
            ->where('app_user_order_capital.order_id', $data['orderId'])
            ->where('app_user.origin', "<>", 2)
            ->where('app_user.shortcut', 1)
            ->where('app_user_order_capital.capital_id', $data['capitalId'])
            ->whereNull('app_user_order_capital.deleted_at')->find();
        if (!empty($list) && $data['state'] == 1) {
            r_date(null, 300, "有师傅没标记工时，无法验收通过，如果这个师傅无需施工，请取消派单，或督促师傅标记工时");
        }
        $ConstructionNode = new ConstructionNode();
        $change_work_time = db('order_times')->where('order_id', $data['orderId'])->value('change_work_time');
        $nodeIds          = json_decode($data['nodeIds'], true);
         $nodeIds          = implode( ',',$nodeIds);
        if ($change_work_time > 1748534400) {
            $capitalNode      = $ConstructionNode->toNewExamine($nodeIds, $data['state'], $data['reason'], $data['orderId'], $this->us['user_id'], $data['capitalId']);
         } else {
            $capitalNode      = $ConstructionNode->toExamine($nodeIds, $data['state'], $data['reason'], $data['orderId'], $this->us['user_id']);
        }


        r_date(null, $capitalNode['code'], $capitalNode['msg']);
    }

    /*
     * 巡检确认
     */
    public function inspectionConfirmation()
    {
        $request = Authority::param(['capitalId']);
        $list    = db('app_user_order_capital')
            ->join('capital', 'app_user_order_capital.capital_id=capital.capital_id', 'left')
            ->join('app_user', 'app_user_order_capital.user_id=app_user.id', 'left')
            ->whereNull('app_user_order_capital.deleted_at')
            ->where('capital.capital_id', $request['capitalId'])
            ->field("capital.class_b,capital.labor_cost,capital.ordesr_id,
        CONCAT('[', GROUP_CONCAT(JSON_OBJECT('id',capital.capital_id,'name',app_user.username,'personalPrice',app_user_order_capital.personal_price,'workTime',app_user_order_capital.work_time) SEPARATOR ','), ']') as  content")
        
            ->group('capital.capital_id')
            ->select();
        if (empty($list)) {
            r_date(null, 302, "该清单没有派师傅，请添加");
        }
        foreach ($list as $k => $item) {
            $name                  = json_decode($item['content'], true);
            $list[$k]['workTime']  = array_sum(array_column($name, 'workTime'));
            $list[$k]['laborCost'] = array_sum(array_column($name, 'personalPrice'));
            $list[$k]['content']   = $name;
        }
        $fast_salary = \db('order_setting')->where('order_id', $list[0]['ordesr_id'])->value('fast_salary');
        if ($fast_salary == 2) {
            $listArray               = empty($list) ? null : $list[0];
            $app_user_order_capital = \db('app_user_order_capital')
                ->field('app_user_order_capital.capital_id,app_user_order_capital.created_at')
                ->order('app_user_order_capital.created_at ASC')
                ->group('capital_id')
                ->buildSql();

            $auxiliary_delivery_node = db('auxiliary_delivery_schedule')
                ->field('auxiliary_delivery_schedule.completion_time,app_user_order_capital.created_at')
                ->join('auxiliary_project_list', 'auxiliary_project_list.id=auxiliary_delivery_schedule.auxiliary_project_list_id', 'left')

                ->join([$app_user_order_capital => 'app_user_order_capital'], 'app_user_order_capital.capital_id=auxiliary_delivery_schedule.capital_id', 'left')
                ->where('auxiliary_project_list.capital_id', $request['capitalId'])
                ->where('auxiliary_delivery_schedule.work_process_accept_std_type', 3)
                ->whereNull('auxiliary_project_list.delete_time')
                ->whereNull('auxiliary_delivery_schedule.delete_time')
                ->select();
            $stop_completion_time = [];
            foreach ($auxiliary_delivery_node as $item) {
                if ($item['completion_time'] != 0) {
                    $stop_completion_time[] = $item;
                }
            }

            if (bcsub(count($auxiliary_delivery_node), count($stop_completion_time)) != 1) {
                r_date(null, 200);
            }
            $completion_time = $auxiliary_delivery_node[0]['completion_time'];
            // 计算时间差（以秒为单位）
            $timeDifference = abs($completion_time - $auxiliary_delivery_node[0]['created_at']);
            // 将时间差转换为小时数
            $hours = floor($timeDifference / (60 * 60));
            // 判断是否在24小时内
            $listArray['approvalPrompt'] = "";
            if (!empty($auxiliary_delivery_node) && $hours <= 24) {
                $listArray['approvalPrompt'] = "此清单派单后不足24小时便完工，请确认是否真实完成";
            }
            r_date($listArray, 200);
        }
        r_date(null, 200);
    }

    /**
     * 店长节点上传
     * @param \app\api\model\Common $common
     * @return never
     */
    public function addNode(Common $common)
    {
        $data = Request::instance()->post();


        $change_work_time = db('order_times')->where('order_id', $data['orderId'])->value('change_work_time');
        $ConstructionNode = new ConstructionNode();
        if ($change_work_time > 1748534400) {
            $params   = request()->only(['orderId', 'type', 'lat', 'lng']);
            $resource = json_decode($data['imgList'], true);
            $code = $ConstructionNode->newAdd($params, $common, $resource, $this->us['user_id']);
        } else {
            $params   = request()->only(['order_id', 'title', 'describe', 'lng', 'lat', 'address', 'id']);
            $resource = json_decode($data['resource'], true);
            $code = $ConstructionNode->oldAdd($data, $params, $common, $resource, $this->us['user_id']);
        }
        if ($code['code'] == 200) {
            r_date(null, 200);
        }
        r_date(null, 300, $code['message']);
    }



    public function del()
    {
        $data                    = Request::instance()->post();
        $app_user_order_node     = Db::connect(config('database.db2'))->table('app_user_order_node')->where('find_in_set(:id,resource_ids)', ['id' => $data['nodeId']])->find();
        $auxiliary_delivery_node = db('auxiliary_delivery_node')->where('auxiliary_delivery_schedul_id', $data['id'])->where('node_id', $app_user_order_node['id'])->find();
        $path = db('common_resource')->where('id', $data['nodeId'])->value('path');
        $filename = pathinfo($path)['dirname'] . '/' . pathinfo($path)['filename'] . '_OLD.' . pathinfo($path)['extension'];
        $pathsId = db('common_resource')->where('path', $filename)->value('id');
        $resource_ids = explode(',', $app_user_order_node['resource_ids']);
        $no_watermark_image_ids = explode(',', $app_user_order_node['no_watermark_image_ids']);
        foreach ($resource_ids as $k => $o) {
            if ($o == $data['nodeId']) {
                unset($resource_ids[$k]);
            }
        }
        if (!empty($no_watermark_image_ids)) {
            foreach ($no_watermark_image_ids as $k => $o) {
                if ($o == $pathsId) {
                    unset($no_watermark_image_ids[$k]);
                }
            }
        }
        if (count($resource_ids) == 0) {
            db('auxiliary_delivery_node')->where('auxiliary_delivery_schedul_id', $data['id'])->where('node_id', $app_user_order_node['id'])->delete();
            Db::connect(config('database.db2'))->table('app_user_order_node')->where('id', $auxiliary_delivery_node['node_id'])->delete();
        } else {
            Db::connect(config('database.db2'))->table('app_user_order_node')->where('id', $auxiliary_delivery_node['node_id'])->update(['resource_ids' => implode($resource_ids, ','), 'no_watermark_image_ids' => implode($no_watermark_image_ids, ',')]);
        }
        r_date(null, 200);
    }
    /*
     * a.大于X订单金额的工地，只能拍摄或者上传益鸟应用内水印相机的照片
     * b.小于X订单金额的工地，可以使用手机相册、益鸟水印相册、益鸟水印相机拍摄
     * 1000M
     */
    public function orderAmount()
    {
        $data  = Authority::param(['orderId', 'lat', 'lng']);
        $total_price = Db::connect(config('database.db2'))->table('order_aggregate')->where('order_id', $data['orderId'])->value('total_price');
        $acceptance_watermark_switch = Db::connect(config('database.db2'))->table('order_setting')->where('order_id', $data['orderId'])->value('acceptance_watermark_switch');
        //        $order=Db::connect(config('database.db2'))->table('order')->where('order_id', $data['orderId'])->find();
        //        $completion_acceptance_range=Db::connect(config('database.db2'))->table('order_setting')->where('order_id', $data['orderId'])->value('completion_acceptance_range');
        //        $Difference = getDistance($order['lat'], $order['lng'], $data['lat'], $data['lng']);
        //        if($Difference>1000  && $completion_acceptance_range==1){
        //            r_date(null, 300,'打卡位置超过工地范围1公里,不允许上传');
        //        }
        $set = 1;
        if ($acceptance_watermark_switch == 1) {
            if ($total_price > 10000) {
                $set = 0;
            } else {
                $set = 1;
            }
        }

        r_date($set, 200);
    }
      /**
     * 添加资源返回ID
     * @param $resources
     * @return array
     */
    public function addResourceIds($resources)
    {
        
        $resource_ids = [];
        $resource_old_ids = [];
        $aLi=new  Aliyunoss();
        foreach ($resources as $item) {
            if (!isset($item['mime_type']) || !isset($item['file_path'])) {
                r_date(null, 300, '资源格式错误');
            }
            $info           = Db::connect(config('database.db2'))->table('common_resource')->where('path', $item['file_path'])->find();
            $resource_ids[] = Db::connect(config('database.db2'))->table('common_resource')->insertGetId(['mime_type' => $item['mime_type'], 'path' =>$item['file_path'], 'size' => $item['size'] ?? 0, 'created_at' => time()]);
           
            if(isset($item['oldImg']) && $item['oldImg'] !=''){
                $path=$item['file_path'];
                $filename=pathinfo($path)['dirname'].'/'.pathinfo($path)['filename'].'_OLD.'.pathinfo($path)['extension'];
                $parts = parse_url($item['oldImg']);
                $l=$aLi->copyObject(ltrim($parts['path'],'/'),$filename);
                if ($l['info']['http_code'] != 200) {
                    r_date(null, 300, '图片上传错误');
                }
                $resource_old_ids[] = Db::connect(config('database.db2'))->table('common_resource')->insertGetId(['mime_type' => $item['mime_type'], 'path' => $filename, 'size' => $item['size'] ?? 0, 'created_at' => time()]);
                
            } else{
                $resource_old_ids[] = Db::connect(config('database.db2'))->table('common_resource')->insertGetId(['mime_type' => $item['mime_type'], 'path' => $item['file_path'], 'size' => $item['size'] ?? 0, 'created_at' => time()]);
            }
        }
        return ['resource_ids'=>$resource_ids,'no_watermark_image'=>$resource_old_ids];
    }
}
